import cv2
import numpy as np
import imutils
import scipy.signal as signal
from scipy import ndimage
from matplotlib import pyplot as plt
from rect_detect import rectangle_detect

def grid_patch(img, patch_size, grid):
    # img = cv2.imread(imgpath)
    h, w, _ = img.shape
    img_patches = np.empty(((grid ** 2), patch_size, patch_size, 3), dtype=np.uint8)
    coord = np.empty(((grid ** 2), 4), dtype=np.int)
    x_endsteps = np.linspace(patch_size, w, num=grid)
    y_endsteps = np.linspace(patch_size, h, num=grid)

    for i, ystep in enumerate(y_endsteps):
        for j, xstep in enumerate(x_endsteps):
            xmax = int(xstep)
            ymax = int(ystep)
            xmin = int(xstep - patch_size)
            ymin = int(ystep - patch_size)

            patch_img = img[ymin:ymax, xmin:xmax, :]
            img_patches[i * grid + j, :, :, :] = patch_img
            coord[i * grid + j] = [xmin, ymin, xmax, ymax]

    return img_patches, coord  # [grid**2, H,W,BGR]

def isinrect(pa,pb,pc,pd,pm):
    ab = [pb[0]-pa[0],pb[1]-pa[1]]
    am = [pm[0] - pa[0], pm[1] - pa[1]]
    bc = [pc[0] - pb[0], pc[1] - pb[1]]
    bm = [pm[0] - pb[0], pm[1] - pb[1]]
    cd = [pd[0] - pc[0], pd[1] - pc[1]]
    cm = [pm[0] - pc[0], pm[1] - pc[1]]
    da = [pa[0] - pd[0], pa[1] - pd[1]]
    dm = [pm[0] - pd[0], pm[1] - pd[1]]

    pro1 = ab[0]*am[1]-am[0]*ab[1]
    pro2 = bc[0] * bm[1] - bc[0] * bm[1]
    pro3 = cd[0] * cm[1] - cd[0] * cm[1]
    pro4 = da[0] * dm[1] - da[0] * dm[1]

    if pro1>0 and pro2>0 and pro3>0 and pro4>0:
        return 1
    else:
        return 0

patch_size = (900,600)

img = cv2.imread("data/IMG_3847.JPG")
print img.shape
whole_img = np.zeros((img.shape[0], img.shape[1]),np.uint8)
corners = rectangle_detect(img)
print corners

img_patches, coords = grid_patch(img, 1000, 6)

print img_patches.shape

# for i,patch in enumerate(img_patches):
#
#     plt.subplot(6,6,i+1)
#     plt.imshow(patch[:,:,::-1])
# plt.show()

for patch,coord in zip(img_patches, coords):

# patch = img_patches[21]
# coord = coords[21]
    img_midfilt = ndimage.median_filter(patch, 2)
    gray_ori = cv2.cvtColor(patch, cv2.COLOR_BGR2GRAY)
    gray_filt = cv2.cvtColor(img_midfilt, cv2.COLOR_BGR2GRAY)
    canny =cv2.Canny(gray_filt,70,70*3)

    # plt.figure(figsize=(15,8))
    # plt.subplots_adjust(top=0.95,bottom=0.05,left=0.05,right=0.95,hspace=0.15, wspace=0.01)
    # plt.subplot(221)
    # plt.title('img')
    # plt.imshow(patch)
    # plt.subplot(222)
    # plt.title('img_midfilt')
    # plt.imshow(img_midfilt)
    # plt.subplot(223)
    # plt.title('gray')
    # plt.imshow(gray_ori)
    # plt.subplot(224)
    # plt.title('gray_filt')
    # plt.imshow(gray_filt)


    kernel_d = np.array([[0,1,0],
                         [1,1,1],
                         [0,1,0]
                         ]).astype(np.uint8)
    dilated = cv2.dilate(canny, kernel_d)

    # plt.figure(figsize=(15,8))
    # plt.subplots_adjust(top=0.95,bottom=0.05,left=0.05,right=0.95,hspace=0.15, wspace=0.01)
    #
    #
    # plt.subplot(221)
    # plt.title('canny')
    # plt.imshow(canny)
    #
    # plt.subplot(222)
    # plt.title('dilated')
    # plt.imshow(dilated)

    labeled_img = patch.copy()
    _, contours, hierarchy= cv2.findContours(dilated,mode=cv2.RETR_TREE ,method=cv2.CHAIN_APPROX_SIMPLE)

    ones = np.zeros_like(dilated, np.uint8)
    huahen=[]
    i = 0

    for c in contours:
        i+=1
        a = cv2.contourArea(c)
        if a>500 and a<50000:
            print a
            huahen.append(c)
            x, y, w, h = cv2.boundingRect(c)

            # isinrect(pa=)

    cv2.drawContours(ones, huahen, -1, (1,), cv2.FILLED)
    # plt.subplot(224)
    # plt.title('ones')
    # plt.imshow(ones)
    #
    whole_img[coord[1]:coord[3], coord[0]:coord[2]] = ones



plt.figure(figsize=(15,8))
plt.subplots_adjust(top=0.95,bottom=0.05,left=0.05,right=0.95,hspace=0.15, wspace=0.01)
plt.subplot(221)
plt.title('img')
plt.imshow(img)

plt.subplot(222)
plt.title('whole_img')
plt.imshow(whole_img)

plt.show()